package com.kaifamiao.context;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1、从 ServletContext 中 读取初始化参数
 * 2、通过 ServletContext 存取属性(attribute)
 */
@WebServlet( { "/application/counter" , "/app/counter" } )
public class ApplicationCounterServlet extends HttpServlet {

    @Override
    protected void service( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        // 获得 当前 Web应用(web application) 对应的 ServletContext 对象
        ServletContext application = request.getServletContext();

        // 获取 ServletContext 初始化参数 (通过 web.xml 中的 context-param 配置)
        String attrName = application.getInitParameter( "counterAttributeName" );
        attrName = attrName == null || attrName.trim().isEmpty() ? "counter" : attrName ;

        // 尝试从 application 中获取 counter 属性值
        Integer appCounter = (Integer)application.getAttribute( attrName );
        // 若 appCounter 为 null 则赋予初始值
        if( appCounter == null ) {
            appCounter = 0 ; // auto-boxing
        }
        // 将 appCounter 自增后的值重新设置到 application 属性中
        application.setAttribute( attrName , ++appCounter );

        HttpSession session = request.getSession();

        // 尝试从 session 中获取 counter 属性值
        Integer sessionCounter = (Integer)session.getAttribute( attrName );
        // 若 sessionCounter 为 null 则赋予初始值
        if( sessionCounter == null ) {
            sessionCounter = 0 ; // auto-boxing
        }
        // 将 sessionCounter 自增后的值重新设置到 session 属性中
        session.setAttribute( attrName , ++sessionCounter );

        response.setHeader( "content-type" , "text/html;charset=UTF-8" );
        PrintWriter out = response.getWriter();
        out.println( "<title>计数器</title>" );
        out.println( "<p align='center'>总计 " + appCounter + " 次访问</p>" );
        out.println( "<p align='center'>您是第 " + sessionCounter + " 次访问</p>" );

    }

}
